﻿using System.Windows;
using System.ComponentModel.Composition;
using Tododoo.Lib;
using Tododoo.Data;
using System.Collections.ObjectModel;
using System;
using System.Windows.Input;
using System.Windows.Data;

namespace Tododoo.ViewModels
{
    public class ShellViewModel : ViewModelBase, IRecepient
    {
        private IData _database;
        private ObservableCollection<Thing> _things;

        public ShellViewModel()
        {
            this._database = Services.Get<IData>();
            this.Reload();
            PostOffice.Subscribe(AddThingViewModel.NewThingAdded, this);
        }

        public override string Title
        {
            get
            {
                return "Tododoo";
            }
        }

        public ObservableCollection<Thing> Things
        {
            get { return this._things; }
            set
            {
                this._things = value;
                OnPropertyChanged("Things");
            }
        }

        private void Reload()
        {
            this.Things = new ObservableCollection<Thing>(_database.Things);
            var view = (CollectionView)CollectionViewSource.GetDefaultView(this.Things);
            view.SortDescriptions.Add(new System.ComponentModel.SortDescription { PropertyName = "Created", Direction = System.ComponentModel.ListSortDirection.Descending });
        }

        public bool GotMail(Mail mail, object attachment)
        {
            if (mail == AddThingViewModel.NewThingAdded)
            {
                Thing newThing = (Thing)attachment;
                this.Things.Add(newThing);
            }

            return false;
        }
    }
}
